package com.liu.auto.interceptor;

import com.liu.auto.token.TokenTemplate;
import com.liu.auto.token.ValidResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

public class TokenInterceptor implements HandlerInterceptor {

    @Autowired(required = false)
    TokenTemplate tokenTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("x-token");
        if (null==token){
            error(response,"无权访问！");
            return false;
        }
        //验证token
        ValidResult result = tokenTemplate.validToken(token);
        if (result.getStatus()==0){
            error(response,result.getMsg());
            return false;
        }
        //验证通过 获取用户信息 传递放行
        Map map = result.getPayload();
        return true;
    }

    void error(HttpServletResponse response,String msg){
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        pw.write("{\"code\":0,\"msg\":" + msg + "}");
    }
}
